<?php

use Es\Exceptions\CommonExceptions;
use Es\Operate\Index;
use Es\Constant\{FieldsConst,IndexConst};
use Es\Struct\Fields\{DynamicStruct,IntStruct,StringStruct,DateStruct};
use Es\Struct\{ConnectStruct,IndexMappingsStruct,IndexSettingsStruct,IndexStruct};

include './vendor/autoload.php';

try{
    $index = 'test_v_1';
    deleteIndex($index);
    createIndex($index);
    addDouc($index);
}catch(\Throwable $e){
    var_dump($e->getCode());
    var_dump($e->getMessage());
    var_dump($e->getFile());
    var_dump($e->getLine());
}
/**
 * @throws CommonExceptions
 */
function deleteIndex($indexName){

    $index = new Index(new ConnectStruct());
    if($index->exist($indexName)){
        $res = $index->delete($indexName);
    }
}
function createIndex($indexName){

    $index = new Index(new ConnectStruct());
    if(!$index->exist($indexName)){
        $mappings = (new IndexMappingsStruct())
            ->setDynamic(new DynamicStruct(IndexConst::DYNAMIC_STRICT))
            ->setFields(new IntStruct("u_id", FieldsConst::INT))
            ->setFields(new IntStruct("c_id", FieldsConst::LONG))
            ->setFields(new StringStruct('question', FieldsConst::KEYWORD))
            ->setFields(new StringStruct('answer',FieldsConst::TEXT))
            ->setFields(new DateStruct('add_time',FieldsConst::DATE))
            ->setFields(new DateStruct('edit_time',FieldsConst::DATE));
        $settings = new IndexSettingsStruct(3, 1, "1s", "10000");
        $index->create(new IndexStruct($indexName, $settings, $mappings));
    }
}

/**
 * @throws CommonExceptions
 */
function addDouc($indexName){
    $data = [
        "question" => "你好我是个es问题",
        "answer"   => "你好我是个es回复",
        "u_id"     => 1111,
        "c_id"     => 2222,
        "add_time" => date('Y-m-d H:i:s'),
        "edit_time" => date('Y-m-d H:i:s')
    ];
    $documentStruct = new Es\Struct\DocumentStruct($indexName, $data);
    $document = new Es\Operate\Document(new ConnectStruct(), $documentStruct);
    $res = $document->add();
    var_dump($res);
}

